package boardgamer.common;

import com.google.common.base.Predicate;

import java.util.Iterator;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Cyclic iterator that keeps going next until the element to be returned is valid, as according to
 * the predicate passed in.
 *
 * @author garysoed
 */
public class CheckedCyclicIterator<E> implements Iterator<E> {

  private final CyclicIterator<E> iterator;
  private final Predicate<E> isValidPredicate;

  public CheckedCyclicIterator(List<E> elements, Predicate<E> isValidPredicate) {
    this.iterator = new CyclicIterator<E>(elements);
    this.isValidPredicate = checkNotNull(isValidPredicate, "isValidPredicate");
  }

  @Override
  public boolean hasNext() {
    return iterator.hasNext();
  }

  @Override
  public E next() {
    E nextElement;
    synchronized (iterator) {
      do {
        nextElement = iterator.next();
      } while(!isValidPredicate.apply(nextElement));
    }
    
    return nextElement;
  }

  @Override
  public void remove() {
    iterator.remove();
  }
}
